package com.lanlian.commonlib.base;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;

/**
 * <pre>
 *     author : huxiaobo
 *     e-mail : huxiaobo@xlanlian.com
 *     date   : 2018/9/17 14:54
 *     desc   : todo
 *     version: 1.0
 * </pre>
 */
public abstract class BaseLazyFragment extends BaseFragment {

    //Fragment的View加载完毕的标记
    protected boolean mIsViewCreated;

    //Fragment对用户可见的标记
    protected boolean mIsUIVisible;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mIsViewCreated = true;
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if (isVisibleToUser) {
            mIsUIVisible = true;
            lazyLoad();
        } else {
            mIsUIVisible = false;
        }
    }

    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if (mIsViewCreated && mIsUIVisible) {
            loadData();
            //数据加载完毕,恢复标记,防止重复加载
            mIsViewCreated = false;
        }
    }

    protected abstract void loadData();

}
